class PomodoroTimer {
    constructor() {
        this.timer = {
            minutes: 25,
            seconds: 0,
            isRunning: false,
            interval: null
        };
        
        // 添加任务关联属性
        this.currentTask = null;
        this.taskTimers = new Map();
        
        // 添加状态管理
        this.isMinimized = false;
        this.isMaximized = false;
        
        // 白噪音管理器
        this.whiteNoiseManager = null;
        
        // 铃声配置 - 使用本地音频文件
        this.ringtones = {
            default: {
                name: '默认提示音',
                file: 'bell/ding.mp3'
            },
            bell: {
                name: '清脆铃声',
                file: 'bell/bell.mp3'
            },
            notification: {
                name: '通知音',
                file: 'bell/bell-notification.mp3'
            },
            ding: {
                name: '简约叮声',
                file: 'bell/ding2.mp3'
            },
            doorbell: {
                name: '门铃声',
                file: 'bell/doorbell.mp3'
            },
            electronic: {
                name: '电子门铃',
                file: 'bell/electronic-doorbell.mp3'
            }
        };
        
        this.currentRingtone = 'default';
        this.loadSettings();
        
        // 确保DOM加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.setupTimer();
            });
        } else {
            this.setupTimer();
        }
    }

    setupTimer() {
        // console.log('Setting up timer...');
        
        // 初始化白噪音管理器
        if (typeof WhiteNoiseManager !== 'undefined') {
            this.whiteNoiseManager = new WhiteNoiseManager();
        }
        
        // 设置基础控件
        this.setupBasicControls();
        this.setupDurationButtons();
        this.setupSizeControls();
        this.setupWhiteNoisePanel();
        
        this.updateTimerDisplay();
    }
    
    setupBasicControls() {
        const timerBtn = document.getElementById('timerBtn');
        const ringtoneSelect = document.getElementById('ringtoneSelect');
        const testRingtoneBtn = document.getElementById('testRingtoneBtn');
        
        if (timerBtn) {
            timerBtn.replaceWith(timerBtn.cloneNode(true));
            const newTimerBtn = document.getElementById('timerBtn');
            
            newTimerBtn.addEventListener('click', (e) => {
                e.preventDefault();
                if (this.timer.isRunning) {
                    this.pauseTimer();
                } else {
                    this.startTimer();
                }
            });
        }
        
        if (ringtoneSelect) {
            ringtoneSelect.value = this.currentRingtone;
            ringtoneSelect.addEventListener('change', (e) => {
                this.currentRingtone = e.target.value;
                this.saveSettings();
            });
        }
        
        if (testRingtoneBtn) {
            testRingtoneBtn.addEventListener('click', () => {
                this.testRingtone();
            });
        }
    }
    
    setupSizeControls() {
        const minimizeBtn = document.getElementById('timerMinimizeBtn');
        const maximizeBtn = document.getElementById('timerMaximizeBtn');
        
        if (minimizeBtn) {
            // 克隆并替换按钮以确保事件绑定正确
            minimizeBtn.replaceWith(minimizeBtn.cloneNode(true));
            const newMinimizeBtn = document.getElementById('timerMinimizeBtn');
            newMinimizeBtn.addEventListener('click', () => {
                this.toggleMinimize();
            });
        }
        
        if (maximizeBtn) {
            // 克隆并替换按钮以确保事件绑定正确
            maximizeBtn.replaceWith(maximizeBtn.cloneNode(true));
            const newMaximizeBtn = document.getElementById('timerMaximizeBtn');
            newMaximizeBtn.addEventListener('click', () => {
                this.toggleMaximize();
            });
        }
    }
    
    setupWhiteNoisePanel() {
        if (!this.whiteNoiseManager) return;
        
        const noiseControls = document.getElementById('noiseControls');
        const stopAllBtn = document.getElementById('noiseStopAllBtn');
        
        if (noiseControls) {
            this.renderWhiteNoiseControls();
        }
        
        if (stopAllBtn) {
            stopAllBtn.addEventListener('click', () => {
                this.whiteNoiseManager.stopAll();
                this.renderWhiteNoiseControls();
            });
        }
    }
    
    renderWhiteNoiseControls() {
        const noiseControls = document.getElementById('noiseControls');
        if (!noiseControls || !this.whiteNoiseManager) return;
        
        const noiseList = this.whiteNoiseManager.getNoiseList();
        
        noiseControls.innerHTML = noiseList.map(noise => `
            <div class="noise-item">
                <button class="noise-toggle ${noise.isPlaying ? 'active' : ''}" 
                        data-noise="${noise.key}">
                </button>
                <span class="noise-name">${noise.name}</span>
                <div class="noise-volume-control">
                    <input type="range" 
                           class="noise-volume-slider" 
                           min="0" 
                           max="1" 
                           step="0.1" 
                           value="${noise.volume}"
                           data-noise="${noise.key}">
                    <span class="noise-volume-value">${Math.round(noise.volume * 100)}%</span>
                </div>
            </div>
        `).join('');
        
        // 绑定事件
        noiseControls.querySelectorAll('.noise-toggle').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const noiseKey = e.target.dataset.noise;
                this.whiteNoiseManager.toggleNoise(noiseKey);
                this.renderWhiteNoiseControls();
            });
        });
        
        noiseControls.querySelectorAll('.noise-volume-slider').forEach(slider => {
            slider.addEventListener('input', (e) => {
                const noiseKey = e.target.dataset.noise;
                const volume = parseFloat(e.target.value);
                this.whiteNoiseManager.setVolume(noiseKey, volume);
                
                // 更新显示
                const valueSpan = e.target.nextElementSibling;
                valueSpan.textContent = `${Math.round(volume * 100)}%`;
            });
        });
    }
    
    toggleMinimize() {
        const timerElement = document.getElementById('pomodoroTimer');
        const minimizeBtn = document.getElementById('timerMinimizeBtn');
        
        this.isMinimized = !this.isMinimized;
        
        if (this.isMinimized) {
            timerElement.classList.add('minimized');
            timerElement.classList.remove('maximized');
            minimizeBtn.innerHTML = '<i class="fas fa-plus"></i>';
            minimizeBtn.title = '还原';
            this.isMaximized = false;
        } else {
            timerElement.classList.remove('minimized');
            minimizeBtn.innerHTML = '<i class="fas fa-minus"></i>';
            minimizeBtn.title = '最小化';
        }
        
        this.updateWhiteNoisePanelVisibility();
    }
    
    toggleMaximize() {
        // console.log('Toggling maximize...'); // 调试日志
        const timerElement = document.getElementById('pomodoroTimer');
        const maximizeBtn = document.getElementById('timerMaximizeBtn');
        
        this.isMaximized = !this.isMaximized;
        
        if (this.isMaximized) {
            timerElement.classList.add('maximized');
            timerElement.classList.remove('minimized');
            maximizeBtn.innerHTML = '<i class="fas fa-compress"></i>';
            maximizeBtn.title = '还原';
            this.isMinimized = false;
        } else {
            timerElement.classList.remove('maximized');
            maximizeBtn.innerHTML = '<i class="fas fa-expand"></i>';
            maximizeBtn.title = '最大化';
        }
        
        this.updateWhiteNoisePanelVisibility();
    }
    
    updateWhiteNoisePanelVisibility() {
        const whiteNoisePanel = document.getElementById('whiteNoisePanel');
        if (whiteNoisePanel) {
            whiteNoisePanel.style.display = this.isMaximized ? 'block' : 'none';
        }
    }

    // 新增：设置时长选择按钮
    setupDurationButtons() {
        const durationButtons = document.querySelectorAll('.duration-btn');
        
        durationButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                
                // 如果计时器正在运行，不允许更改时长
                if (this.timer.isRunning) {
                    alert('计时器正在运行中，无法更改时长');
                    return;
                }
                
                // 移除所有按钮的 active 类
                durationButtons.forEach(b => b.classList.remove('active'));
                
                // 为当前按钮添加 active 类
                btn.classList.add('active');
                
                // 获取选择的分钟数
                const minutes = parseInt(btn.dataset.minutes);
                
                // 设置计时器时长
                this.setCustomDuration(minutes);
                
                // 保存设置
                this.saveCustomDuration(minutes);
            });
        });
        
        // 加载保存的时长设置
        this.loadCustomDuration();
    }

    // 新增：设置自定义时长
    setCustomDuration(minutes) {
        this.timer.minutes = minutes;
        this.timer.seconds = 0;
        this.updateTimerDisplay();
    }

    // 新增：保存自定义时长
    saveCustomDuration(minutes) {
        const settings = JSON.parse(localStorage.getItem('pomodoroSettings') || '{}');
        settings.customDuration = minutes;
        localStorage.setItem('pomodoroSettings', JSON.stringify(settings));
    }

    // 新增：加载自定义时长
    loadCustomDuration() {
        const settings = JSON.parse(localStorage.getItem('pomodoroSettings') || '{}');
        const customDuration = settings.customDuration || 25; // 默认25分钟
        
        // 设置计时器时长
        this.setCustomDuration(customDuration);
        
        // 更新按钮状态
        const durationButtons = document.querySelectorAll('.duration-btn');
        durationButtons.forEach(btn => {
            btn.classList.remove('active');
            if (parseInt(btn.dataset.minutes) === customDuration) {
                btn.classList.add('active');
            }
        });
    }

    async playRingtone() {
        try {
            const ringtone = this.ringtones[this.currentRingtone];
            if (!ringtone || !ringtone.file) {
                this.showNotification();
                return;
            }
            
            const audio = new Audio(ringtone.file);
            audio.volume = 0.7;
            await audio.play();
        } catch (error) {
            console.warn('播放铃声失败:', error);
            this.showNotification();
        }
    }

    // 试听铃声功能
    async testRingtone(ringtoneName = null) {
        const ringtoneToTest = ringtoneName || this.currentRingtone;
        const ringtone = this.ringtones[ringtoneToTest];
        
        if (!ringtone || !ringtone.file) {
            console.warn('铃声文件不存在:', ringtoneToTest);
            return;
        }
        
        try {
            const audio = new Audio(ringtone.file);
            audio.volume = 0.7;
            await audio.play();
        } catch (error) {
            console.warn('试听铃声失败:', error);
        }
    }

    showNotification() {
        if (Notification.permission === 'granted') {
            new Notification('番茄时钟', {
                body: '专注时间已完成！',
                icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%23ff4757"/></svg>'
            });
        } else {
            alert('番茄时钟完成！专注时间结束');
        }
    }

    loadSettings() {
        const settings = JSON.parse(localStorage.getItem('pomodoroSettings') || '{}');
        this.currentRingtone = settings.ringtone || 'default';
        // 移除这里的时长设置，因为会在 setupDurationButtons 中处理
    }

    resetTimer() {
        // console.log('Resetting timer...'); // 调试日志
        
        this.pauseTimer();
        
        // 重置到当前选择的时长，而不是固定的 25 分钟
        const settings = JSON.parse(localStorage.getItem('pomodoroSettings') || '{}');
        const customDuration = settings.customDuration || 25;
        
        this.timer.minutes = customDuration;
        this.timer.seconds = 0;
        this.updateTimerDisplay();
    }

    saveSettings() {
        const settings = {
            ringtone: this.currentRingtone
        };
        localStorage.setItem('pomodoroSettings', JSON.stringify(settings));
    }

    startTimer() {
        // console.log('Starting timer...'); // 调试日志
        
        this.timer.isRunning = true;
        const timerBtn = document.getElementById('timerBtn');
        if (timerBtn) {
            timerBtn.innerHTML = '<i class="fas fa-pause"></i>';
        }
        
        this.timer.interval = setInterval(() => {
            // console.log(`Timer: ${this.timer.minutes}:${this.timer.seconds}`); // 调试日志
            
            if (this.timer.seconds === 0) {
                if (this.timer.minutes === 0) {
                    this.timerComplete();
                    return;
                }
                this.timer.minutes--;
                this.timer.seconds = 59;
            } else {
                this.timer.seconds--;
            }
            this.updateTimerDisplay();
        }, 1000);
    }

    pauseTimer() {
        // console.log('Pausing timer...'); // 调试日志
        
        this.timer.isRunning = false;
        if (this.timer.interval) {
            clearInterval(this.timer.interval);
            this.timer.interval = null;
        }
        
        const timerBtn = document.getElementById('timerBtn');
        if (timerBtn) {
            timerBtn.innerHTML = '<i class="fas fa-play"></i>';
        }
    }

    resetTimer() {
        console.log('Resetting timer...'); // 调试日志
        
        this.pauseTimer();
        this.timer.minutes = 25;
        this.timer.seconds = 0;
        this.updateTimerDisplay();
    }

    // 新增：为特定任务启动计时器
    startTaskTimer(task) {
        // 检查计时器状态
        console.log('检查计时器状态:', this.timer.isRunning ? '运行中' : '未运行');
        
        if (this.timer.isRunning) {
            console.log('发现计时器正在运行，询问用户是否停止');
            this.showConfirmModal(
                '当前有计时器正在运行，是否停止并开始新任务？',
                () => {
                    console.log('用户确认停止当前计时器');
                    this.pauseTimer();
                    // 直接在这里启动新任务
                    this.startNewTask(task);
                },
                () => {
                    console.log('用户取消操作，保持当前计时器运行');
                }
            );
            return;
        }
        
        this.startNewTask(task);
    }
    
    // 启动新任务的逻辑
    startNewTask(task) {
        this.currentTask = task;
        
        // 设置计时时间（默认25分钟，如果任务有设置番茄数则使用任务设置）
        const pomodoroMinutes = task.pomodoros ? task.pomodoros * 25 : 25;
        this.timer.minutes = pomodoroMinutes;
        this.timer.seconds = 0;
        
        // 更新显示
        this.updateTimerDisplay();
        
        // 显示当前任务信息
        this.showTaskInfo(task);
        
        // 开始计时
        this.startTimer();
    }

    // 新增：显示确认模态框
    showConfirmModal(message, onConfirm, onCancel) {
        // 创建模态框
        const modal = document.createElement('div');
        modal.className = 'confirm-modal';
        modal.innerHTML = `
            <div class="confirm-dialog">
                <p>${message}</p>
                <div class="modal-buttons">
                    <button class="btn-confirm">确认</button>
                    <button class="btn-cancel">取消</button>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 添加show类来显示模态框
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
        
        // 绑定事件
        modal.querySelector('.btn-confirm').onclick = () => {
            modal.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(modal);
                onConfirm();
            }, 300); // 等待动画完成
        };
        
        modal.querySelector('.btn-cancel').onclick = () => {
            modal.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(modal);
                onCancel();
            }, 300); // 等待动画完成
        };
    }

    // 新增：显示当前任务信息
    showTaskInfo(task) {
        const timer = document.querySelector('.pomodoro-timer');
        const taskContainer = document.getElementById('taskInfoContainer');
        const modeIndicator = document.getElementById('modeIndicator');
        const taskName = document.getElementById('taskName');
        const stopBtn = document.getElementById('stopTaskBtn');
        
        // 显示任务信息
        taskContainer.style.display = 'block';
        taskName.textContent = task.text;
        modeIndicator.textContent = '任务计时';
        
        // 添加任务模式样式
        timer.classList.add('task-mode');
        
        // 绑定停止按钮事件
        stopBtn.onclick = () => {
            this.stopTaskTimer();
        };
    }
    
    hideTaskInfo() {
        const timer = document.querySelector('.pomodoro-timer');
        const taskContainer = document.getElementById('taskInfoContainer');
        const modeIndicator = document.getElementById('modeIndicator');
        
        // 隐藏任务信息
        taskContainer.style.display = 'none';
        modeIndicator.textContent = '自由计时';
        
        // 移除任务模式样式
        timer.classList.remove('task-mode');
    }

    // 新增：停止任务计时
    stopTaskTimer() {
        this.pauseTimer();
        this.currentTask = null;
        
        // 隐藏任务信息
        const taskInfo = document.querySelector('.current-task-info');
        if (taskInfo) {
            taskInfo.remove();
        }
        
        // 隐藏任务信息
        this.hideTaskInfo();

        // 重置计时器
        this.resetTimer();
    }

    // 修改现有的timerComplete方法
    timerComplete() {
        console.log('Timer completed!');
        
        this.pauseTimer();
        
        // 播放提示音
        this.playRingtone();
        
        // 显示通知
        if (Notification.permission === 'granted') {
            const taskName = this.currentTask ? this.currentTask.text : '番茄时钟';
            new Notification('番茄时钟完成', {
                body: this.currentTask ? `任务「${taskName}」专注时间已完成！` : '25分钟专注时间已完成！',
                icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%23ff4757"/></svg>',
                silent: true
            });
        } else {
            const taskName = this.currentTask ? this.currentTask.text : '番茄时钟';
            alert(`番茄时钟完成！${this.currentTask ? `任务「${taskName}」` : ''}专注时间结束`);
        }
        
        // 如果有关联任务，自动完成任务
        if (this.currentTask) {
            this.completeCurrentTask();
        }
        
        this.resetTimer();
    }

    // 新增：完成当前任务
    completeCurrentTask() {
        if (this.currentTask && window.app) {
            // 自动完成任务
            window.app.toggleTask(this.currentTask.id);
            
            // 显示任务完成提示
            if (Notification.permission === 'granted') {
                new Notification('任务完成', {
                    body: `任务「${this.currentTask.text}」已自动完成！`,
                    icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%2300d2d3"/></svg>',
                    silent: true
                });
            }
            
            // 清除任务关联
            this.currentTask = null;
            
            // 隐藏任务信息
            const taskInfo = document.querySelector('.current-task-info');
            if (taskInfo) {
                taskInfo.remove();
            }
        }
    }

    updateTimerDisplay() {
        const display = document.getElementById('timerDisplay');
        if (display) {
            const minutes = this.timer.minutes.toString().padStart(2, '0');
            const seconds = this.timer.seconds.toString().padStart(2, '0');
            display.textContent = `${minutes}:${seconds}`;
        } else {
            console.warn('Timer display element not found!');
        }
    }
}
